<?php


namespace app\common\utils;


use app\common\lib\Redis;
use catcher\exceptions\FailedException;

class Str
{

    public static function alphaID(int $len): string
    {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $randPwd = '';
        for ($i = 0; $i < $len; $i++) {
            try {
                $randPwd .= $chars[random_int(0, strlen($chars) - 1)];
            } catch (\Exception $e) {
                throw new FailedException("随机串获取失败");
            }
        }
        return $randPwd;

    }

    public static function getAnswerNo(): int
    {
        if (Redis::getInstance()->redis->exists("answerNo")) {
            $answerNo = Redis::getInstance()->redis->incr("answerNo");
        } else {
            $answerNo = 100000000;
            Redis::getInstance()->redis->set("answerNo", $answerNo);
        }
        return $answerNo;
    }

    public static function filterEmpty(array $args): string
    {
        $str = '';
        foreach ($args as $k => $v) {
            if (!empty($v)) {
                $str .= $v;
            }
        }
        return $str;
    }

    /**
     * 数据脱敏
     */
    public static function desensitize($string, $start = 0, $length = 0, $re = '*')
    {
        if(empty($string) || empty($length) || empty($re)) return $string;
        $end = $start + $length;
        $strlen = mb_strlen($string);
        $str_arr = array();
        for($i=0; $i<$strlen; $i++) {
            if($i>=$start && $i<$end)
                $str_arr[] = $re;
            else
                $str_arr[] = mb_substr($string, $i, 1);
        }
        return implode('',$str_arr);
    }

    /**
     * 计算天数
     * @param string $start_date 开始日期
     * @param string $end_date 结束日期
     * @return int
     */
    public static function calculateDays(string $start_date, string $end_date): int
    {
        $date1 = strtotime($start_date);
        $date2 = strtotime($end_date);

        $diff = $date2 - $date1;
        return floor($diff / (60 * 60 * 24));
    }
}